using UnityEngine;
using QFramework;
using System.Linq;
using QAssetBundle;

namespace ProjectSurvivor
{
	public partial class SimpleKnife : ViewController
	{
		void Start()
		{
			// Code Here
		}

		float mCurrentSeconds = 0;


        private void Update()
        {
			mCurrentSeconds += Time.deltaTime;

			if(mCurrentSeconds >= Global.SimpleKnifeDuration.Value)
			{
				mCurrentSeconds = 0;

                if (Player.Default)
                {

                    var enemies = FindObjectsOfType<Enemy>().OrderBy(enemy => Player.Default.Distance2D(enemy))
                        .Take(Global.SimpleKnifeCount.Value);

                    var i = 0;
                   foreach(Enemy enemy in enemies)
                    {
                        if (i < 4)
                        {
                            ActionKit.DelayFrame(11 * i, () =>
                            {
                            AudioKit.PlaySound(Sfx.KNIFE);
                            }).StartGlobal();
                          i++;
                        }
                    if (enemy)
                    {
                        Knife.Instantiate()
                            .Position(this.Position())
                            .Show()
                            .Self(self =>
                            {
                                var selfCache = self;
                                var direction=enemy.NormalizedDirection2DFrom(Player.Default);
                                self.transform.up = direction;
                                var rigibody2D = self.GetComponent<Rigidbody2D>();
                                rigibody2D.velocity = direction * 10;

                                self.OnTriggerEnter2DEvent(collider =>
                                {
                                    var hurBox = collider.GetComponent<HurtBox>();
                                    if (hurBox)
                                    {
                                        if (hurBox.Owner.CompareTag("Enemy"))
                                        {
                                            hurBox.Owner.GetComponent<Enemy>().Hurt(Global.SimpleKnifeDamage.Value);
                                            selfCache.DestroyGameObjGracefully();
                                        }
                                    }
                                }).UnRegisterWhenGameObjectDestroyed(self);


                                ActionKit.OnUpdate.Register(() =>
                                {
                                    if ((Player.Default.Distance2D(selfCache)) > 20)
                                    {
                                        selfCache.DestroyGameObjGracefully();
                                    }
                                }).UnRegisterWhenGameObjectDestroyed(self);
                            });
                    }
                    }
                }
            }
        }
    }
}
